package com.dingup.paike.controller.feedback;

import com.alibaba.fastjson.JSON;
import com.dingup.api.Util.DateUtil;
import com.dingup.api.adapter.classInfo.ClassInfoAdapter;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.enums.ExamTypeEnum;
import com.dingup.api.model.sys.SysUser;
import com.dingup.paike.adapter.pk.PkLessonInfoAdapter;
import com.dingup.paike.dao.*;
import com.dingup.paike.enums.PkLessonUserTypeEnum;
import com.dingup.paike.enums.TemplateTypeEnum;
import com.dingup.paike.feign.client.classInfo.ClassInfoFeignClient;
import com.dingup.paike.feign.client.user.UserFeignClient;
import com.dingup.paike.model.feedback.*;
import com.dingup.paike.model.pk.PkLessonStudentSign;
import com.dingup.paike.model.pk.PkLessonUser;
import com.dingup.paike.schedule.FeedbackSchedule;
import com.dingup.paike.service.message.DingTalkMsgService;
import com.suyeer.basic.util.BHttpResUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.dingup.api.base.BaseUtil.*;
import static com.dingup.paike.util.ConstUtil.*;

/**
 * Created by wancheng on 2018/6/21.
 */
@Controller
@RequestMapping("/feedback")
public class FeedbackController {


    @Autowired
    TsFeedbackTemplateMapper tsFeedbackTemplateMapper;
    @Autowired
    TsFeedbackContentMapper tsFeedbackContentMapper;
    @Autowired
    TsFeedbackStudentEvaluateMapper tsFeedbackStudentEvaluateMapper;
    @Autowired
    PkLessonInfoMapper pkLessonInfoMapper;
    @Autowired
    UserFeignClient userFeignClient;
    @Autowired
    ClassInfoFeignClient classInfoFeignClient;
    @Autowired
    FeedbackSchedule feedbackSchedule;
    @Autowired
    PkLessonStudentSignMapper pkLessonStudentSignMapper;
    @Autowired
    PkLessonUserMapper pkLessonUserMapper;
    @Autowired
    DingTalkMsgService dingTalkMsgService;

    private Logger logger = LoggerFactory.getLogger(FeedbackController.class);

    /**
     * 获取老师和学生的信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/get_teacher_and_student.do", method = RequestMethod.POST)
    public void getFeedbackTeacherAndStudentMsg(HttpServletRequest request,
                                                HttpServletResponse response,
                                                Integer lessonId) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取老师或学生");
        try {
            PkLessonInfoAdapter lessonInfo = pkLessonInfoMapper.getPkLessonInfoForFully(lessonId);
            if (lessonInfo == null) {
                throw new Exception("无此课程信息");
            }
            if (lessonInfo.getIfPreLesson()) {
                throw new Exception("此课节为预排课");
            }
            Integer classId = lessonInfo.getClassId();
            ClassInfoAdapter classInfo = classInfoFeignClient.getClassInfoById(classId);
            Map<String, String> exam = classInfo.getExam();
            String subjectName = lessonInfo.getSubjectName();
            ExamTypeEnum subjectType = ExamTypeEnum.getEnumByDescription(subjectName);
            if (subjectName == null) {
                //返回自定义
                subjectType = ExamTypeEnum.DEFINESELF;
            }
            List<PkLessonUser> users = lessonInfo.getUsers();
            Map<PkLessonUserTypeEnum, List<PkLessonUser>> userTypeMap = users.stream().collect(Collectors.groupingBy(PkLessonUser::getType));
            Map<String, Object> res = new HashMap<>();
            res.put("teacher", userTypeMap.get(PkLessonUserTypeEnum.TEACHER).get(0));
            res.put("students", userTypeMap.get(PkLessonUserTypeEnum.STUDENT));
            res.put("exam", exam);
            res.put("subjectType", ExamTypeEnum.getMap(subjectType.name()));
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 获取模版信息
     *
     * @param request
     * @param response
     * @param examType
     * @param subjectType
     * @param classType
     */
    @RequestMapping(value = "/get_template.do", method = RequestMethod.POST)
    public void isBind(HttpServletRequest request,
                       HttpServletResponse response,
                       @RequestParam(REQUEST_PARAMETER_EXAM_TYPE) String examType,
                       @RequestParam(REQUEST_PARAMETER_SUBJECT_TYPE) String subjectType,
                       @RequestParam(REQUEST_PARAMETER_CLASS_TYPE) String classType) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取反馈模版");
        try {
            checkParam(REQUEST_PARAMETER_EXAM_TYPE, examType);
            checkParam(REQUEST_PARAMETER_SUBJECT_TYPE, subjectType);
            checkParam(REQUEST_PARAMETER_CLASS_TYPE, classType);
            Map<String, Object> res = new HashMap<>();
            examType = examType.toUpperCase();
            classType = classType.toUpperCase();
            subjectType = subjectType.toUpperCase();
            //上课内容
            List<TsFeedbackTemplate> lessonContent = tsFeedbackTemplateMapper.selectByTypes(examType, subjectType, classType, TemplateTypeEnum.LESSONCONTENT.name());
            //学生课堂表现
            List<TsFeedbackTemplate> lessonRepresentation = tsFeedbackTemplateMapper.selectByTypes(null, null, null, TemplateTypeEnum.LESSONREPRESENTATION.name());
            //作业反馈
            List<TsFeedbackTemplate> homeworkFeedback = tsFeedbackTemplateMapper.selectByTypes(examType, subjectType, null, TemplateTypeEnum.HOMEWORKFEEDBACK.name());

            List<TsFeedbackTemplate> sqList = tsFeedbackTemplateMapper.selectByTypes(examType, subjectType, null, TemplateTypeEnum.SUBJECTQUESTION.name());
            //学科问题
            List<JSON> subjectQuestion = new ArrayList<>();

            for (TsFeedbackTemplate f : sqList) {
                String template = f.getTemplateContent();
                template = template.replaceAll("\\\\六", "六");
                subjectQuestion.add(JSON.parseObject(template));
            }
            res.put("lessonContent", lessonContent);
            res.put("lessonRepresentation", lessonRepresentation);
            res.put("homeworkFeedback", homeworkFeedback);
            res.put("subjectQuestion", subjectQuestion);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 验证反馈是否重复提交
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/check.do", method = RequestMethod.POST)
    public void check(HttpServletRequest request,
                      HttpServletResponse response,
                      @RequestParam(REQUEST_PARAMETER_LESSON_ID) Integer lessonId) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("验证反馈是否提交");
        try {
            Boolean ifConfirm = false;
            TsFeedbackContent tsFeedbackContent = tsFeedbackContentMapper.selectByLessonId(lessonId);
            if (tsFeedbackContent != null) {
                ifConfirm = true;
            }
            saveSuccessMsgAndData(hrc, ifConfirm);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 教师提交反馈
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/teacher_confirm.do", method = RequestMethod.POST)
    public void confirm(HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam(REQUEST_PARAMETER_FEEDBACK) String feedbackJson) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("老师提交反馈");
        try {
            Map<String, Object> res = new HashMap<>();
            Feedback feedback = JSON.parseObject(feedbackJson, Feedback.class);
            TsFeedbackContent tsFeedbackContent = tsFeedbackContentMapper.selectByLessonId(feedback.getLessonId());
            Boolean ifInsert = false;
            if (tsFeedbackContent != null) {
                res.put("result", false);
                res.put("msg", "已存在当前反馈的提交");
            } else {
                try {
                    ifInsert = insert(feedback);
                    res.put("result", true);
                    res.put("msg", "提交成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info(e.getMessage());
                    res.put("result", false);
                    res.put("msg", "提交失败");
                }
            }
            if (ifInsert) {
                //提交成功后向班主任发送微信消息
                PkLessonInfoAdapter pkLessonInfoAdapter = pkLessonInfoMapper.getPkLessonInfoForFully(feedback.getLessonId());
                Map<PkLessonUserTypeEnum, List<PkLessonUser>> userTypeMap = pkLessonInfoAdapter.getUsers()
                        .stream().collect(Collectors.groupingBy(PkLessonUser::getType));
                PkLessonUser teacher = userTypeMap.get(PkLessonUserTypeEnum.TEACHER).get(0);
                List<PkLessonUser> students = userTypeMap.get(PkLessonUserTypeEnum.STUDENT);
                for (PkLessonUser student : students) {
                    List<String> parentOpenIds = userFeignClient.getParentWxOpenId(student.getUserId());
                    for (String openId : parentOpenIds) {

                        //此处发送
                        try {
                            feedbackSchedule.sendParentMsg(pkLessonInfoAdapter, student, openId);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //给班主任发送消息
                List<PkLessonUser> master = userTypeMap.get(PkLessonUserTypeEnum.MASTER);
                String studentNames = students.stream().map(PkLessonUser::getUserName).collect(Collectors.joining(" "));
                if (master != null) {
                    master.forEach(
                            m -> {
                                dingTalkMsgService.sendMsgAfterClassUrlForMaster(m, pkLessonInfoAdapter);
                            }
                    );
                }
            }
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }


    /**
     * 教师提交反馈
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/not_should_feedback.do", method = RequestMethod.POST)
    public void notShouldFeedback(HttpServletRequest request,
                                  HttpServletResponse response,
                                  @RequestParam(REQUEST_PARAMETER_LESSON_ID) Integer lessonId) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("老师提交反馈");
        try {
            Map<String, Object> res = new HashMap<>();
            TsFeedbackContent tsFeedbackContent = tsFeedbackContentMapper.selectByLessonId(lessonId);
            if (tsFeedbackContent != null) {
                res.put("result", false);
                res.put("msg", "已存在当前反馈的提交");
            } else {
                try {

                    res.put("result", true);
                    res.put("msg", "提交成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    res.put("result", false);
                    res.put("msg", "提交失败");
                }
            }
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public Boolean insert(Feedback feedback) {
        TsFeedbackContent tsFeedbackContent = new TsFeedbackContent();
        tsFeedbackContent.setCreateTime(new Date());
        tsFeedbackContent.setClasstype(feedback.getClassTypeType());
        tsFeedbackContent.setExam(feedback.getExamType());
        tsFeedbackContent.setSubject(feedback.getSubjectType());
        tsFeedbackContent.setLessoncontent(feedback.getLessonContent());
        tsFeedbackContent.setLessonName(feedback.getLessonName());
        tsFeedbackContent.setLessonId(feedback.getLessonId());
        tsFeedbackContent.setHomeWork(feedback.getHomeWork());
        tsFeedbackContentMapper.insertSelective(tsFeedbackContent);
        for (StudentEvaluate s : feedback.getStudentEvaluates()) {
            TsFeedbackStudentEvaluateWithBLOBs tsStudent = new TsFeedbackStudentEvaluateWithBLOBs();
            tsStudent.setCreateTime(new Date());
            tsStudent.setHomeworkFeedback(s.getHomeworkFeedback());
            tsStudent.setLessonRepresentation(s.getLessionRepresentation());
            tsStudent.setStudentId(s.getStudentId());
            tsStudent.setSubjectQuestions(s.getSubjectQuestions());
            tsStudent.setFeedbackId(tsFeedbackContent.getId());
            tsFeedbackStudentEvaluateMapper.insertSelective(tsStudent);
        }
        return true;
    }

    /**
     * 家长获取反馈内容
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/get_student_feedback.do", method = RequestMethod.POST)
    public void studentFeedback(HttpServletRequest request,
                                HttpServletResponse response,
                                @RequestParam(REQUEST_PARAMETER_STUDENT_ID) String studentId,
                                @RequestParam(REQUEST_PARAMETER_LESSON_ID) Integer lessonId) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("家长获取反馈信息");
        try {
            Map<String, Object> res = new HashMap<>();
            TsFeedbackContent tsFeedbackContent = tsFeedbackContentMapper.selectByLessonId(lessonId);
            if (tsFeedbackContent == null) {
                throw new Exception("无此反馈信息,学生id=" + studentId + " 课程id" + lessonId);
            }
            TsFeedbackContent ts = tsFeedbackContentMapper.selectByLessonId(lessonId);
            if (ts == null) {
                throw new Exception("老师尚未反馈，request:" + request.getQueryString());
            }
            TsFeedbackStudentEvaluateWithBLOBs tsfeed = tsFeedbackStudentEvaluateMapper.selectStudentEvaluate(ts.getId(), studentId);
            if (ts == null) {
                throw new Exception("改课程反馈无此学生信息，request:" + request.getQueryString());
            }
            PkLessonInfoAdapter pkLessonInfoAdapter = pkLessonInfoMapper.getPkLessonInfoForFully(lessonId);
            String className = classInfoFeignClient.getSimpleClassInfo(pkLessonInfoAdapter.getClassId()).getClassName();
            PkLessonStudentSign studentSign = pkLessonStudentSignMapper.getByPkLessonIdAndStudentId(lessonId, studentId);
            PkLessonUser teacher = pkLessonUserMapper.getByPkLessonIdAndType(lessonId, null, PkLessonUserTypeEnum.TEACHER);
            //选择需要的数据
            Map<String, Object> returnLesson = new HashMap<>();
            returnLesson.put("beginTime", DateUtil.getDTS(pkLessonInfoAdapter.getBeginTime()));
            returnLesson.put("endTime", DateUtil.getDTS(pkLessonInfoAdapter.getEndTime()));
            returnLesson.put("lessonName", ts.getLessonName());
            SysUser student = userFeignClient.getUserByUserId(tsfeed.getStudentId());
            res.put("teacherName", teacher.getUserName());
            res.put("lesson", returnLesson);
            res.put("lessonContent", ts);
            res.put("evaluate", tsfeed);
            res.put("studentName", student.getUserName());
            res.put("studentId", student.getUserId());
            res.put("className", className);
            if (studentSign != null) {
                //签到时间
                res.put("signInTime", studentSign.getSignTime());
            }
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 半注入获取反馈内容
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/classTeacher_feedback.do", method = RequestMethod.POST)
    public void classTeacherFeedback(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam(REQUEST_PARAMETER_LESSON_ID) Integer lessonId) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("班主任获取反馈信息");
        try {
            Map<String, Object> res = new HashMap<>();
            TsFeedbackContent tsFeedbackContent = tsFeedbackContentMapper.selectByLessonId(lessonId);
            if (tsFeedbackContent == null) {
                throw new Exception("无此反馈信息, " + " 课程id" + lessonId);
            }
            TsFeedbackContent ts = tsFeedbackContentMapper.selectByLessonId(lessonId);
            if (ts == null) {
                throw new Exception("老师尚未反馈，request:" + request.getQueryString());
            }
            List<TsFeedbackStudentEvaluateWithBLOBs> tsfeed = tsFeedbackStudentEvaluateMapper.getByFeedbackId(ts.getId());
            if (ts == null) {
                throw new Exception("改课程反馈无此学生信息，request:" + request.getQueryString());
            }
            PkLessonInfoAdapter lesson = pkLessonInfoMapper.getPkLessonInfoForFully(lessonId);
            PkLessonUser teacher = pkLessonUserMapper.getByPkLessonIdAndType(lessonId, null, PkLessonUserTypeEnum.TEACHER);
            tsfeed.forEach(
                    t -> {
                        t.setStudentName(userFeignClient.getUserNameByUserId(t.getStudentId()));
                    }
            );
            String className = null;
            //选择需要的数据
            Map<String, Object> returnLesson = new HashMap<>();
            returnLesson.put("beginTime", DateUtil.getDTS(lesson.getBeginTime()));
            returnLesson.put("endTime", DateUtil.getDTS(lesson.getEndTime()));
            returnLesson.put("lessonName", ts.getLessonName());
            res.put("teacherName", teacher.getUserName());
            res.put("lesson", returnLesson);
            res.put("lessonContent", ts);
            res.put("evaluate", tsfeed);
            res.put("className", className);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }
}
